package cn.yaboya.org.service.impl;

import cn.yaboya.basic.constant.BaseConstants;
import cn.yaboya.basic.exception.BusinessException;
import cn.yaboya.basic.service.Impl.BaseServiceImpl;
import cn.yaboya.basic.utils.*;
import cn.yaboya.org.domain.Employee;
import cn.yaboya.org.domain.Shop;
import cn.yaboya.org.domain.ShopAuditLog;
import cn.yaboya.org.mapper.EmployeeMapper;
import cn.yaboya.org.mapper.ShopAuditLogMapper;
import cn.yaboya.org.mapper.ShopMapper;
import cn.yaboya.org.service.IEmployeeService;
import cn.yaboya.org.service.IShopService;
import cn.yaboya.basic.vo.ShopVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaboya
 * @since 2022-07-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
    * @Title: settlement
    * @Description: 店铺注入实现
    * @Author: LT
    * @Version: 1.0
    * @Date:  2022/7/1 16:42
    * @Parameters: [shop]
    * @Return void
    */
    @Override
    @Transactional
    public void settlement(Shop shop) {

        Employee admin = shop.getAdmin();

        if (StringUtils.isEmpty(shop.getName()) && StringUtils.isEmpty(shop.getTel())){
            throw new BusinessException("参数不能为空");
        }
        if (!admin.getPassword().equals(admin.getComfirmPassword())) {
            throw new BusinessException("密码输入一致");
        }

        // 3.查询店铺是否存在,根据店铺名称查询
        Shop loadShopTmp = shopMapper.loadByName(shop.getName());
        if (loadShopTmp != null){
            throw new BusinessException("店铺已存在，请更改信息");
        }
        /*Boolean censor = BaiduAuditUtils.TextCensor(shop.getName());
        if (!censor) {
            throw new BusinessException("你的店铺名称非法 请输入合格");
        }*/

        // 4.查询管理员是否注册过
        Employee employee = employeeMapper.loadByRepetition(admin);

        if (employee != null && employee.getShopId() !=null) {
            throw new BusinessException("该管理员已绑定店铺，请更换其他管理员！");
        }

        // 1.判断手机号不为空
        if(StringUtils.isEmpty(admin.getPhone())){
            throw new BusinessException("手机号不能为空");
        }

        // 3.判断手机验证码不为空
        if(StringUtils.isEmpty(admin.getSmsCodeValue())){

            throw new BusinessException("手机验证码不能为空");
        }
        // 4.判断密码验证码不为空
        if(StringUtils.isEmpty(admin.getPassword())){
            throw new BusinessException("密码不能为空");
        }
        // 判断密码是否一致
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次密码不一致重新输入");
        }
        // 3判断注册手机号和获取手机号验证码时的号码是否一致

        String smsCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + admin.getPhone();
        // 3.2根据k值(传过来的手机号业务建 判断之前是否有过存在3分种没)获取值，如果获取不到就代表手机号验证码错误或已过期 代表不是本人或这过期

        Object  smsCodeValueTmp = redisTemplate.opsForValue().get(smsCodeKey);
        // 代表已经过期
        if (smsCodeValueTmp == null){
            throw new BusinessException("验证码已过期，请重新输入");
        }
        // 4判断短信验证的号码是否一致
        // 4.1获取Reids短信验证码
        String[] split = smsCodeValueTmp.toString().split(":");
        String smsCode = split[0];
        // 4.2判断是否存在不存在则已过期
        if(!smsCode.equalsIgnoreCase(admin.getSmsCodeValue())){
            throw new BusinessException("验证码错误，请重新输入");
        }

        // 5.查询没有注册 则注册管理员

        if (employee == null){
            employeeService.add(admin);
            employee = admin;

        }
        // 6.已经注册成功
        // 6.1 将管理员的主键设置到店铺的外键
        shop.setAdminId(employee.getId());
        // 6.2 保存店铺 且返回主键
        shopMapper.add(shop);
        // 6.3 店铺主键设置为管理员的外键
        employee.setShopId(shop.getId());
        // 6.4 保存店铺
        employeeService.update(employee);
    }

    /**
    * @Title: pass
    * @Description: 审核通过
    * @Author: LT
    * @Version: 1.0
    * @Date:  2022/7/2 16:16
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    public void pass(ShopAuditLog shopAuditLog) {
        // 1。修改店铺信息为未激活
        // 2. 保存店铺操作日志
        // 2.1 暂时将操作任意id写死
        shopAuditLog.setAuditId(334);
        // 2.2 设置店铺状态为未激活
        Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        shop.setState(2);
        shopMapper.update(shop);

        // 2.3 调用日志日志写入
        shopAuditLogMapper.add(shopAuditLog);

        // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
        String text = "你好你的店铺审核已通过,请点击激活，激活才可以正常使用" +
                "激活链接：<a href= 'http://localhost:8080/shop/audit/"+shopAuditLog.getShopId()
                +"'>点我激活店铺</a>";
        MailUtils.sendMail("253223090@qq.com", text, "测试啦");
    }

    /**
    * @Title: reject
    * @Description: 店铺驳回接口
    * @Author: LT
    * @Version: 1.0
    * @Date:  2022/7/2 16:52
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    public void reject(ShopAuditLog shopAuditLog) {
        // 1。修改店铺信息为未激活
        // 2. 保存店铺操作日志
        // 2.1 暂时将操作任意id写死
        shopAuditLog.setAuditId(334);
        // 2.2 设置店铺状态为驳回
        Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        shop.setState(-1);
        shopMapper.update(shop);
        // 2.3 调用日志日志写入
        shopAuditLogMapper.add(shopAuditLog);
        // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
        String text = "你好你的店铺审核未通过已被驳回,请重新填表单" +
                "失败原因" + shopAuditLog.getNote() +
                "修改链接：<a href= 'http://localhost:8081/shopRegisterAgain?shopId()="+shopAuditLog.getShopId()+"'>x点我激活店铺</a>";
        MailUtils.sendMail("253223090@qq.com", text, "测试啦");
    }

    @Override
    public void insertBatchShop(List<Shop> shops) {
        shopMapper.insertBatchShop(shops);
    }

    @Override
    public Map<String, Object> loadShopEchartsData() {
        List<ShopVo> shopVos =  shopMapper.loadShopEchartsData();

        List<String> states = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        for (ShopVo shopVo : shopVos) {
            if (1 == shopVo.getState()){
                states.add("以审核");
            }
            if (0 == shopVo.getState()){
                states.add("待审核");
            }
            if (-1 == shopVo.getState()){
                states.add("驳回");
            }if (2 == shopVo.getState()){
                states.add("待激活");
            }
            counts.add(shopVo.getCountNum());
        }
        System.out.println(states.toString());

        HashMap<String, Object> data = new HashMap<>();
        data.put("x", states);
        data.put("y", counts);
        return data;
    }

    /**
    * @Title: refuse
    * @Description: 审核拒绝
    * @Author: LT
    * @Version: 1.0
    * @Date:  2022/7/2 23:07
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    public void refuse(ShopAuditLog shopAuditLog) {
        // 1。修改店铺信息为未激活
        // 2. 保存店铺操作日志
        // 2.1 暂时将操作任意id写死
        shopAuditLog.setAuditId(334);
        // 2.2 设置店铺状态为未激活
        Shop shop = shopMapper.loadById(shopAuditLog.getShopId());
        shop.setState(3);
        shopMapper.update(shop);
        // 2.3 调用日志日志写入
        shopAuditLogMapper.add(shopAuditLog);
        // 3.发送邮件通知审核已通过
        // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
        String text = "你好你的店铺审核已被拒绝,请你正确使用店铺";
        MailUtils.sendMail("253223090@qq.com", text, "测试啦");
    }

    @Override
    public void smsCode(Employee employee) {
        String phone = employee.getPhone();
        // 1.判断参数是否为空
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("参数错误请重新输入");
        }

        // 跳过图形验证嘛
        // 拼接手机业务键
        String smsCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + phone;
        Object smsCodeValueTmp = redisTemplate.opsForValue().get(smsCodeKey);

        // 4.2 判断验证码是否为空 或者已过期 为空则生成新的验证码
        String smsCode = "";
        // 4.2.1如果验证码 为空 则代表用户第一次获取 直接生成四位随机码即可
        // 不为空 则第一步判断时间是否超过一分钟 超过才能重新获取 小于则提示用户
        // 超过一分钟 重新获取 我们使用之前的随机码即可
        if (smsCodeValueTmp == null) {
            smsCode = StrUtils.getComplexRandomString(4);
        } else {
            // 4.2.2 截取业务键值 的值 取到电话号码
            String[] smsCodeValueArray = smsCodeValueTmp.toString().split(":");
            // 4.2.3 获取老的时间戳
            Long oldTime = Long.valueOf(smsCodeValueArray[1]);
            // 4.2.4 获取现在的时间戳
            Long nowTime = System.currentTimeMillis();
            // 判断时间是否超过一分钟
            if (nowTime - oldTime <= 1*60*1000) {
                throw new BusinessException("请一分钟重试");
            }
            // 判断是否超过一分钟
            smsCode = smsCodeValueArray[0];
        }
        // 6.设置时间为三分钟 到redis
        String smsCodeValue = smsCode + ":" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(smsCodeKey, smsCodeValue, 3, TimeUnit.MINUTES);
        // 7.发送验证码
//        SmsUtils.sendMsg(phone, "你的验证码是"+ smsCode);

        System.out.println("你的验证码是"+ smsCode);

    }

    /**
     * @Title: registerVo2User
     * @Description: 封装成一个user类
     * @Author: LT
     * @Version: 1.0
     * @Date:  2022/7/5 14:27
     * @Parameters: [registerVo]
     * @Return cn.yaboya.user.domain.User
     */

}
